from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework.decorators import action
from question.utils import get_token_user
from .serializers import *


class SpitViewSet(ModelViewSet):
    queryset = Spit.objects.all()
    serializer_class = SpitSerializers

    # pagination_class = Mypage

    # 获取所有吐槽
    def list(self, request, *args, **kwargs):
        queryset = self.queryset.filter(parent=None)
        serializers = self.get_serializer(queryset, many=True)
        datas = serializers.data
        if not request.auth:
            return Response(datas)
        # 登录用户要能看到收藏和点赞
        data_dicts = {}
        for data in datas:
            data_dicts[data['id']] = data  # 将列表中的字典转化为已id为键的字典，方便查找
        user = get_token_user(request)
        sus = SpitUser.objects.filter(userid=user.id)
        for su in sus:
            sid = su.spitid
            try:  # 评论点赞用出错过滤
                if su.type == 1:
                    data_dicts[sid]['collected'] = True  # 收藏
                else:
                    data_dicts[sid]['hasthumbup'] = True  # 点赞
            except:
                pass
        return Response(data_dicts.values())

    # 创键吐槽或评论
    def create(self, request, *args, **kwargs):
        data = request.data
        if request.auth:
            user = get_token_user(request)
            data['userid'] = user.id
            data['nickname'] = user.username
            if user.avatar:
                data['avatar'] = user.avatar
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        if request.auth:
            # 回复数+1
            parent = data.get('parent')
            pspit = Spit.objects.get(id=parent)
            pspit.comment += 1
            pspit.save()
        return Response({'success': True, 'message': 'ok'})

    # 获取评论详情
    @action(methods=['get'], detail=True)
    def children(self, request, pk):
        # 浏览数+1
        pspit = Spit.objects.get(id=pk)
        pspit.visits += 1
        pspit.save()
        queryset = self.queryset.filter(parent=pk)
        serializer = self.get_serializer(queryset, many=True)
        datas = serializer.data
        if not request.auth:
            return Response(datas)
        # 登录用户要能看到收藏和点赞
        data_dicts = {}
        for data in datas:
            data_dicts[data['id']] = data  # 将列表中的字典转化为已id为键的字典，方便查找
        user = get_token_user(request)
        sus = SpitUser.objects.filter(userid=user.id)
        for su in sus:
            sid = su.spitid
            try:  # 评论点赞用出错过滤
                if su.type == 1:
                    data_dicts[sid]['collected'] = True  # 收藏
                else:
                    data_dicts[sid]['hasthumbup'] = True  # 点赞
            except:
                pass
        return Response(data_dicts.values())

    def retrieve(self, request, *args, **kwargs):
        # 获取当前吐槽,判断当前用户是否点赞过
        spit = self.get_object()
        su = ''
        if request.auth:
            user = get_token_user(request)
            su = SpitUser.objects.filter(type=2, userid=user.id, spitid=str(spit.id))
        if su:
            spit.hasthumbup = True
        serializer = self.get_serializer(spit)
        return Response(serializer.data)

    @action(methods=['put'], detail=True)
    def collect(self, request, pk):
        if not request.auth:
            return Response({'success': False, 'message': '未登录'})
        user = get_token_user(request)  # 登录用户
        # 获取数据，获取到了就是收藏的，1为收藏
        su = SpitUser.objects.filter(type=1, userid=user.id, spitid=pk)
        spit = self.get_object()
        if su:
            su.delete()
        else:
            SpitUser.objects.create(type=1, userid=user.id, spitid=pk)
        return Response({'success': True, 'message': 'ok'})

    @action(methods=['put'], detail=True)
    def updatethumbup(self, request, pk):
        if not request.auth:
            return Response({'success': False, 'message': '未登录'})
        user = get_token_user(request)  # 登录用户
        # 获取数据，获取到了就是点赞的，2为点赞
        su = SpitUser.objects.filter(type=2, userid=user.id, spitid=pk)
        spit = self.get_object()
        if su:  # 存在取消赞
            su.delete()
            if spit.thumbup > 0:
                spit.thumbup -= 1
                spit.save()
        else:  # 不存在点了赞
            SpitUser.objects.create(type=2, userid=user.id, spitid=pk)
            spit.thumbup += 1
            spit.save()
        return Response({'success': True, 'message': 'ok'})
